package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.constants.RegexPatterns;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String KEY_PREFIX = "ly:user:phone:";

    @Override
    public void sendVerifyCode(String phone) {
        Map<String, String> msg = new HashMap<>();

        // 2.使用Apache的工具类生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("phone", phone);
        msg.put("code", code);

        this.amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        //redis存储5min
        this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

    }

    @Override
    public Boolean checkExists(String data, Integer type) {


        if (StringUtils.isBlank(data)) {
            throw new LyException(400, "请求参数有误");
        }

        User user = new User();

        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                if (data.matches(RegexPatterns.PHONE_REGEX)) {
                    user.setPhone(data);
                } else {
                    throw new LyException(400, "请求参数有误");
                }
                break;
            default:
                throw new LyException(400, "请求参数有误");
        }


        //select count(id) from tb_user where username = ldh or phone=13032200000
        boolean result = query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;

        return result;
    }


    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();

        //判断输入的验证码和获得的验证码是否相同
        if (!StringUtils.equals(code, redisTemplate.opsForValue().get(key))) {
            throw new LyException(400, "验证码无效");
        }

        //加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        //解析，根据密文，推演出盐值，拿明文和盐值二次加密，获得密文，获得后进行比对
        //passwordEncoder.matches("mingwen","miwen");

        user.setPassword(encodePassword);
        save(user);

        //删除无效key
        redisTemplate.delete(key);

    }

    @Override
    public UserDTO queryUserByNameAndPass(String username, String password) {

        //根据用户名查询
        User user = query().eq("username", username).one();

        //如果查询为空或者查询获取到的加密密码和输入的明文密码不匹配，则抛异常
        if (null == user || !passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "用户名或密码错误");
        }

        return new UserDTO(user);
    }

    /**
     * 1,动态加载到唯一key，（被加载时候要对请求者进行校验，校验通过，才提供key）
     * 2，有了key就应该把 JwtUtils自动初始化，在注入之前，先要初始化jwtUtils
     */
}
